/**
 * 清理表单数据中的 null、''、undefined、空数组
 */
export function cleanFormData<T extends Record<string, any>>(form: T): Partial<T> {
  const result: Partial<T> = {};

  for (const key in form) {
    const val = form[key];
    const isEmptyArray = Array.isArray(val) && val.length === 0;
    if (val !== null && val !== undefined && val !== "" && !isEmptyArray) {
      result[key] = val;
    }
  }

  return result;
}

/**
 * 还原表单数据（将后端数据填充到表单中，支持嵌套属性、默认值）
 */
export function restoreForm<T extends Record<string, any>>(targetForm: T, sourceData: Partial<T>, defaultValue: any = ""): T {
  const result = { ...targetForm };

  for (const key in result) {
    result[key] = sourceData[key] !== undefined ? sourceData[key] : defaultValue;
  }

  return result;
}

/**
 * 重置表单（将所有字段设为初始值，可自定义默认值）
 */
export function resetForm<T extends Record<string, any>>(form: T, defaultValue: any = ""): T {
  const result = { ...form };

  Object.keys(result).forEach(key => {
    (result as any)[key] = defaultValue;
  });

  return result;
}

/**
 * 提取表单中需要的字段（常用于编辑接口前提交）
 */
export function pickFormFields<T extends Record<string, any>>(form: T, keys: Array<keyof T>): Partial<T> {
  const result: Partial<T> = {};

  keys.forEach(key => {
    result[key] = form[key];
  });

  return result;
}
